package com.sxf.controller.blog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.sxf.util.SysLogUtil;

/**
 * 文件上传
 * 
 * @author phsxf01
 * 
 */
@Controller("fileController")
@RequestMapping("file")
public class FileController {

	/**
	 * 单文件上传
	 * 
	 * @param name
	 * @RequestParam 取得name字段的值
	 * @param file
	 *            文件
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/oneFileUpload", method = RequestMethod.POST)
	@ResponseBody
	public String oneFileUpload(@RequestParam("name") String name,
			@RequestParam("file") MultipartFile file) throws Exception {
		SysLogUtil.debug("name：" + name);
		if (file != null && !file.isEmpty()) {
			SysLogUtil.debug("上传文件：" + file.getOriginalFilename());
			copyFile(file);
		}
		return "file/upload_success";
	}

	/**
	 * 多文件上传
	 * 
	 * @param request
	 * @param name
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/multipartFileUpload", method = RequestMethod.POST)
	public String multipartFileUpload(MultipartRequest request,
			@RequestParam("name") String name // 页面上的控件值
	) throws Exception {
		List<MultipartFile> files = request.getFiles("file");
		for (int i = 0; i < files.size(); i++) {
			if (!files.get(i).isEmpty()) {
				SysLogUtil.info("上传文件：" + files.get(i).getOriginalFilename());
				this.copyFile(files.get(i).getInputStream(), files.get(i)
						.getOriginalFilename());
			}
		}
		SysLogUtil.info("success");
		return "file/upload_success";
	}

	/**
	 * 文件下载
	 * 
	 * @param request
	 * @param name
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/download")
	public void download(WebRequest request, HttpServletResponse response)
			throws Exception {
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("");
		File f = new File(new URI(url.toURI().toString()
				+ "../lib/dom4j-1.6.1.jar"));
		System.out.println(f.getAbsolutePath());
		System.out.println(f.getCanonicalPath());
		System.out.println(f.getPath());
		String filePath = f.getCanonicalPath();
		downloadFile(response, filePath, null);
	}

	/**
	 * 写文件到本地
	 * 
	 * @param in
	 * @param fileName
	 * @throws IOException
	 */
	private void copyFile(InputStream in, String fileName) throws Exception {
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("");
		URI uri = url.toURI();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
		File directory = new File(new URI(uri.toString() + "../../upload/"
				+ sdf.format(new Date())));
		if (!directory.exists()) {
			directory.mkdirs();
		}
		String path = directory.getCanonicalPath();
		FileOutputStream fs = new FileOutputStream(path + File.separator
				+ fileName);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;// 总字节数
		int byteread = 0;
		while ((byteread = in.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		SysLogUtil.debug("总字节数:" + bytesum);
		fs.close();
		in.close();
	}

	/**
	 * 写文件到本地
	 * 
	 * @param in
	 * @param fileName
	 * @throws IOException
	 */
	private void copyFile(MultipartFile file) throws Exception {
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("");
		URI uri = url.toURI();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
		File directory = new File(new URI(uri.toString() + "../../upload/"
				+ sdf.format(new Date())));
		if (!directory.exists()) {
			directory.mkdirs();
		}
		String path = directory.getCanonicalPath();
		file.transferTo(new File(path + File.separator
				+ file.getOriginalFilename()));
	}

	/**
	 * @param response
	 * @param filePath
	 * @param fileName
	 *            文件名 可以为null,则取filePath的文件名
	 * @throws Exception
	 */
	private void downloadFile(HttpServletResponse response, String filePath,
			String fileName) throws Exception {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			if (!StringUtils.hasText(fileName)) {
				fileName = file.getName();
			}
			response.setContentType("application/x-download;charset=utf-8");
			String filenameDisplay = URLEncoder.encode(fileName, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename="
					+ filenameDisplay);
			response.setContentLength((int) file.length());
			OutputStream out = response.getOutputStream();
			FileInputStream in = new FileInputStream(file);
			byte[] buffer = new byte[1024 * 512];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();
			in.close();
			out.close();
			System.gc();// 执行完成，调用垃圾回收，此处读写文件（特别是大型文件）会相当消耗内存，所以此处最好做一次回收处理
		}
	}
}
